package logview;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SmartAddLogServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static transient final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(SmartAddLogServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<File> files = new ArrayList<File>();
	
		try {
			final String tomcatHome = System.getProperties().getProperty("catalina.home");
			if (tomcatHome != null) {
				File logsDir = new File(tomcatHome+File.separatorChar+"logs");
				if (logsDir.exists() && logsDir.isDirectory()) {
					files.addAll(Arrays.asList(logsDir.listFiles()));
				}
			}
		} catch (Exception unused) {
		}

		try {
			final String resinHome = System.getProperties().getProperty("resin.home");
			if (resinHome != null) {
				File logsDir = new File(resinHome+File.separatorChar+"logs");
				if (logsDir.exists() && logsDir.isDirectory()) {
					files.addAll(Arrays.asList(logsDir.listFiles()));
				}
			}
		} catch (Exception unused) {
		}

		Collections.sort(files);
		req.setAttribute("List", files);
		req.getRequestDispatcher("/smartadd.jsp").forward(req, resp);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public void init(ServletConfig config) throws ServletException {
		log.debug(SmartAddLogServlet.class.getName()+" initialized");
	}
	
	@Override
	public void destroy() {
		log.debug(SmartAddLogServlet.class.getName()+" destroyed");
		super.destroy();
	}
}
